package com.coldtech.circlecrash;

import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

import com.coldtech.circlecrash.units.Unit;

public class Selection {
	private Screen screen = null;
	private Player player = null;
	private Point2D.Double start = null;
	private Point2D.Double min = null;
	private Point2D.Double max = null;
	private List<Unit> selUnits = null;
	private boolean isSelecting;
	private boolean isSelected;

	public Selection(CircleCrash game) {
		this.screen = game.getScreen();
		this.player = game.getPlayer();
		this.isSelecting = false;
		this.isSelected = false;

		this.start = new Point2D.Double(0, 0);
		this.min = new Point2D.Double(0, 0);
		this.max = new Point2D.Double(0, 0);
		this.selUnits = new ArrayList<Unit>();
	}

	public void startSelection(int minx, int miny) {
		if (this.selUnits.size() > 0) {
			for (int i = 0; i < this.selUnits.size(); i++) {
				this.selUnits.get(i).setSelected(false);
			}
		}
		this.selUnits.clear();

		this.isSelecting = true;
		this.start.setLocation(minx, miny);
		this.min.setLocation(minx, miny);
		this.max.setLocation(minx, miny);
	}

	public void updateSelection(int x, int y) {
		if (x >= this.start.getX()) {
			this.max.setLocation(x, this.max.getY());
		} else {
			this.min.setLocation(x, this.min.getY());
		}

		if (y >= this.start.getY()) {
			this.max.setLocation(this.max.getX(), y);
		} else {
			this.min.setLocation(this.min.getX(), y);
		}
	}

	public void stopSelection(int x, int y) {
		if (this.isSelecting) {
			updateSelection(x, y);
			setSelectedUnits();
			this.isSelected = (this.selUnits.size() > 0);
		}
		this.isSelecting = false;
	}

	public void setSelectedUnits() {
		Unit unit = null;
		List<Unit> units = this.player.getUnits();
		for (int i = 0; i < units.size(); i++) {
			unit = units.get(i);
			if (unit.isControlable()) {
				if ((unit.getPosition().getX() >= this.min.getX() && unit
						.getPosition().getX() <= this.max.getX())
						&& (unit.getPosition().getY() >= this.min.getY() && unit
								.getPosition().getY() <= this.max.getY())) {
					this.selUnits.add(unit);
					unit.setSelected(true);
				}
			}
		}
	}
	
	public void moveSelectedTo(int x, int y) {
		for(int i = 0; i < this.selUnits.size(); i++) {
			this.selUnits.get(i).moveTo(x, y);
		}
	}

	public List<Unit> getSelectedUnits() {
		return this.selUnits;
	}

	public void draw() {
		this.screen.drawSelection(this);
	}

	public int getMinX() {
		return (int) this.min.getX();
	}

	public int getMinY() {
		return (int) this.min.getY();
	}

	public int getMaxX() {
		return (int) this.max.getX();
	}

	public int getMaxY() {
		return (int) this.max.getY();
	}

	public boolean isSelecting() {
		return this.isSelecting;
	}

	public boolean isSelected() {
		return this.isSelected;
	}
}
